package com.kangfawei.io;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

public class CommonsIOTest {
    public static void main(String[] args) {
        try {
            // 将文件读取到字符串
            String msg = FileUtils.readFileToString(new File("E:/IO_src/test01.txt"),"UTF-8");
            System.out.println(msg);
            System.out.println("-------------------------------------------");

            // 将文件逐行读取，返回一个字符串数组
            List<String> strs = FileUtils.readLines(new File("E:/IO_src/test01.txt"), "UTF-8");
            for (String str:strs) {
                System.out.println(str);
            }
            System.out.println("---------------------------------------------");

            // 将文件读取到字节数组中
            byte[] bytes = FileUtils.readFileToByteArray(new File("E:/IO_src/test01.txt"));
            System.out.println(new String(bytes));

            // 将字符串写到文件中
            String str = "This is a new book";
            FileUtils.write(new File("E:/IO_target/commonsIO.txt"),str,"UTF-8",true);

            // 文件复制
            FileUtils.copyFile(new File("E:/IO_src/test01.txt"),new File("E:/IO_target/testCopy.txt"));

            // 将文件复制到文件夹
            FileUtils.copyFileToDirectory(new File("E:/IO_src/test01.txt"),new File("E:/IO_target"));

            // 将文件夹复制到文件夹
            FileUtils.copyDirectoryToDirectory(new File("E:/IO_src"),new File("E:/IO_target"));

            // 复制文件夹
            FileUtils.copyDirectory(new File("E:/IO_src"),new File("E:/IO_target/test"));

            // 复制网页源码到文件
            FileUtils.copyURLToFile(new URL("https://www.taobao.com/"),new File("E:/IO_target/taobao.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
